package com.yonyou.ucf.mdd.ext.util.login;

import com.yonyou.diwork.service.session.extend.ISessionManagerExtendService;
import com.yonyou.diwork.service.session.extend.vo.ContextInfo;
import com.yonyou.iuap.formula.common.SpringContextHolder;
import com.yonyou.ucf.mdd.common.exceptions.message.MddMsgBaseException;
import com.yonyou.ucf.mdd.common.exceptions.message.MddYhtSdkMsgException;
import com.yonyou.ucf.mdd.common.exceptions.message.MsgExceptionCode;
import com.yonyou.ucf.mdd.core.developer.tool.Tracker;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Seraph
 * @Description:
 * @date 2021/5/169:53 PM
 * @email 13718938509@139.com
 */
public class FetchLoginFromNewYht implements FetchLoginUserHandler {
    private static final Logger logger = LoggerFactory.getLogger(FetchLoginFromNewYht.class);


    @Override
    public ContextInfo fetchLoginUser(String token) throws BusinessException {
        return getUserAndIdentityByToken(token);
    }

    /**
     * 从友户通获取用户信息，如果需要获取身份信息调用新的接口
     * 本地换成40s，防止友户通被打死
     *
     * @param accessToken 友户通的token
     * @return
     * @throws MddMsgBaseException
     */
    public static ContextInfo getUserAndIdentityByToken(String accessToken) throws BusinessException {
        //截取时间戳，yxyToken切换租户token带有时间戳，调用yht需要去掉
        ISessionManagerExtendService sessionManagerService = SpringContextHolder.getBean(ISessionManagerExtendService.class);
        ContextInfo contextInfo = sessionManagerService.getMddContext(accessToken);
        Tracker.recordLogClues("com.yonyou.ucf.mdd.ext.util.login.FetchLoginFromNewYht", "getUserAndIdentityByToken",accessToken, contextInfo,"sessionManagerService.getMddContext(accessToken) 结果");
        String ythInfo = contextInfo.getYthInfo();
        if (StringUtils.isEmpty(ythInfo) || "null".equalsIgnoreCase(ythInfo) || contextInfo.getIdentity() == null) {
            logger.error("com.yonyou.ucf.mdd.ext.util.login.FetchLoginFromNewYht.getUserAndIdentityByToken", contextInfo.getMsg());
            if (StringUtils.isEmpty(ythInfo) || "null".equalsIgnoreCase(ythInfo)){
                throw new MddYhtSdkMsgException("友户通返回信息为空, msg:" + contextInfo.getMsg());
            }
            if (contextInfo.getIdentity() == null){
                throw new MddYhtSdkMsgException("友户通身份信息为空, msg:" + contextInfo.getMsg());
            }

        } else {
            if (contextInfo.getStatus() == 1) {
                return contextInfo;
            } else {
                logger.error("通过accessToken获取用户信息失败: {} , token : {}", contextInfo.getMsg(), accessToken);
                throw new MddYhtSdkMsgException(MsgExceptionCode.GET_USER_BY_ACCESSTOKEN_FAIL, new String[]{contextInfo.getMsg()});
            }
        }
        return contextInfo;
    }
}
